package com.hxgis.oc.controller;

import com.hxgis.auw.ApiWrapIgnore;
import com.hxgis.oc.util.fdb.FDB;
import com.hxgis.oc.util.fdb.FDBManager;
import com.hxgis.oc.util.ResponseHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;

@Slf4j
@ApiWrapIgnore
@RestController
@RequiredArgsConstructor
@RequestMapping("/OCMapCacher")
public class OCMapController {
    @Autowired
    ResourceLoader resourceLoader;

    @RequestMapping(value="/cesium/{}")
    public  ResponseEntity<Object> getTerrain(String x,String y,String l) throws IOException {
        HttpHeaders headers = null;

        byte[] res = null;
        String fileName = "";

        if( x== null || y== null || l== null)
        {
            Resource resource = resourceLoader.getResource("classpath:CesiumTerrain.json");
            InputStream is = resource.getInputStream();
            res = new byte[is.available()];
            is.read(res);
            is.close();
            fileName = "CesiumTerrain.json";
        }
        else
        {
            FDB fdb = FDBManager.getFDB("cest");
            if(fdb != null)
            {
                res = fdb.get(x,y,l);
                fileName = x + ".jpg";
            }
        }

        if(res!=null)
        {
            headers = ResponseHelper.createFileHeader(fileName,res.length);
        }

        return new ResponseEntity<>(res, headers, res == null ? HttpStatus.NOT_FOUND : HttpStatus.OK);
    }

    @RequestMapping(value="/vt")
    public ResponseEntity<Object> getGoogle(String lyrs,String x,String y,String z) {
        HttpHeaders headers = new HttpHeaders();

        byte[] res = null;
        String fileName = "";

        if( x!= null && y!= null && z!= null)
        {
            String map = lyrs;
            String [] sv = map.split("@");
            if(sv.length > 0)
            {
                map = sv[0];
            }
            FDB fdb = FDBManager.getFDB("google_" + map);
            if(fdb != null)
            {
                res = fdb.get(x,y,z);
            }
            fileName = x + ".jpg";
        }

        if(res!=null)
        {
            headers = ResponseHelper.createFileHeader(fileName,res.length);
        }

        return new ResponseEntity<>(res, headers, res == null ? HttpStatus.NOT_FOUND : HttpStatus.OK);
    }
}
